package com.learner.major.service;


import com.alibaba.fastjson.JSON;
import com.learner.common.exception.ExceptionUtil;
import com.learner.common.exception.RestException;
import com.learner.major.common.MajorUtil;
import com.learner.major.common.UpdateUtil;


import com.learner.pojo.major.Major;
import com.learner.major.repository.MajorRepository;


import com.learner.common.util.CodeMsg;
import com.learner.common.util.Result;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;

/**
 * @author ice2020x
 * @Date: 2023/3/7
 * @Description:
 **/
@Slf4j
@Service
public class MajorService {

    @Autowired
    private MajorRepository majorRepository;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加专业信息
     *
     * @param major 专业信息
     * @return major
     */
    public Major addMajorInf(Major major) {
        log.info("添加专业信息：" + JSON.toJSONString(major));
        return majorRepository.save(major);
    }


    /**
     * 专业信息修改
     *
     * @param major 专业信息
     * @return major
     */
    public Major updateUser(Major major) {
        Major save = null;

        if (StringUtils.isBlank(major.getId())) {
            //参数绑定异常异常（空）
            throw ExceptionUtil.createException(RestException.class, 4200001);
        }

        String id = major.getId();
        Optional<Major> optional = majorRepository.findById(id);

        if (!(optional.isPresent())) {
            //没有这个id
            throw ExceptionUtil.createException(RestException.class, 4200002);
        }
        Major oldInfo = optional.get();
        //如果oldUser不为空
        if (!(MajorUtil.isNullForUpdate(oldInfo))) {
            //修改的字段覆盖原对象
            UpdateUtil.copyNullProperties(major, oldInfo);
            //更新到数据库
            major = majorRepository.save(oldInfo);

        }
        return major;
    }


    /**
     * 查询全部专业信息
     *
     * @return 查询结果
     */
    public List<Major> selectAll() {
        return majorRepository.findAll();
    }


    /**
     * 根据id查询专业信息
     *
     * @param id id
     * @return 查询结果
     */
    public Major selectById(String id) {
        log.info("根据id查询专业信息，id为:{}", id);
        Optional<Major> optional = majorRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        throw ExceptionUtil.createException(RestException.class, 4200002);
    }

    /**
     * 根据id逻辑删除
     *
     * @param id id
     * @return 删除结果
     */
    public long logicDeleteById(String id) {

        if (StringUtils.isBlank(id)) {
            throw ExceptionUtil.createException(RestException.class, 4200001);
        }

        Query query = Query.query(Criteria.where("_id").is(id));

        Update update = new Update();

        update.set("status", "2");
        //直接操纵mongodb的字段
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Major.class);

        if (!updateResult.isModifiedCountAvailable()) {
            //没有这个id
            throw ExceptionUtil.createException(RestException.class, 4200001);
        }
        return updateResult.getModifiedCount();

    }


    /**
     * 模糊查询
     *
     * @param name
     * @return
     */
    public List<Major> findByLikelyName(String name) {
        log.info("模糊查询，关键字：{}", name);
        if (StringUtils.isBlank(name)) {
            throw ExceptionUtil.createException(RestException.class, 4200001);
        }
        //正则匹配
        Pattern pattern = Pattern.compile(".*?" + MajorUtil.escapeExprSpecialWord(name).toString() + ".*");
        Criteria criteria = Criteria.where("majorName").regex(pattern);
        Query query = new Query(criteria);
        return mongoTemplate.find(query, Major.class);
    }


}
